package com.nd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nd.common.result.ResultUtils;
import com.nd.entity.Product;
import com.nd.entity.Users;
import com.nd.service.IProductService;
import com.nd.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liruirui
 * @since 2024-12-25
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService service;

    /**
     * 分页查询--后台
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/")
    public Object getList(Integer page,Integer limit){
        Page p = new Page(page,limit);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("weight");
        IPage ipage = service.page(p,queryWrapper);
        int total = (int)ipage.getTotal(); //总条数
        List records = ipage.getRecords(); //当前页的数据
        return ResultUtils.returnSuccessLayui(records,total);
    }

    /**
     * 查询菜品列表--前台
     * @return
     */
    @GetMapping("/forFront")
    public Object getList(){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sale_on_off",1);
        queryWrapper.orderByDesc("weight");
        return ResultUtils.returnDataSuccess(service.list(queryWrapper));
    }

    /**
     * 根据id查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Object getById(@PathVariable("id")Integer id){
        return service.getById(id);
    }

    /**
     * 根据id删除单个
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Object del(@PathVariable("id")Integer id){
        if(service.removeById(id)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("删除失败");
        }
    }


    /**
     * 添加
     * @param p
     * @return
     */
    @PostMapping("/")
    public Object add(@RequestBody Product p){
        if(service.save(p)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("添加失败");
        }
    }



    /**
     * 修改
     * @param p
     * @return
     */
    @PutMapping("/")
    public Object update(@RequestBody Product p){
        if(service.updateById(p)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("修改失败");
        }
    }

}
